import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

const _axios = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
})
let cancelArr = []
_axios.interceptors.request.use(
  (config) => {
    // console.log('config', config)
    // 取消同一个api接口的上次请求
    cancelArr = cancelArr.filter((item) => {
      if (item.url === config.url && item.method === config.method) {
        item.cancel()
        return false
      }
      return true
    })

    config.cancelToken = new axios.CancelToken((cancel) => {
      cancelArr.push({
        url: config.url,
        method: config.method,
        cancel
      })
    })

    // token令牌统一处理
    if (store.state.user.token) {
      config.headers.Authorization = `Bearer ${store.state.user.token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

_axios.interceptors.response.use(
  (res) => {
    if (res.data.success) {
      // Message.success(res.data.message)
      return res.data
    } else {
      Message.error(res.data.message)
      return Promise.reject(res.data.message)
    }
  },
  (error) => {
    if (error.response && error.response.status === 401) {
      store.commit('user/mutLogout')
      router.push('/login?redirect=' + location.href.split('#')[1])
    }
    return Promise.reject(error)
  }
)

export default _axios
export function canceled() {
  cancelArr = cancelArr.filter((item) => {
    item.cancel()
    return false
  })
}
